<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="en">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-xm.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-xm.ico?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">










<meta name="description" content="网路编程网络编程基础计算机网络 多台计算机通过通讯线路相连接  互联网 将所有计算机网络相连接  协议  TCP IP    IP地址 标识一个网络接口  一台接入互联网的计算机至少有一个IP地址 我感觉应该是一块无线网卡对应一个ip地址  分类  按格式  IPV4  32位整数 耗尽   IPV6    按范围  公网 内网（局域网）">
<meta property="og:type" content="article">
<meta property="og:title" content="网络编程">
<meta property="og:url" content="http://yoursite.com/2020/05/09/网络编程/index.html">
<meta property="og:site_name" content="Ming">
<meta property="og:description" content="网路编程网络编程基础计算机网络 多台计算机通过通讯线路相连接  互联网 将所有计算机网络相连接  协议  TCP IP    IP地址 标识一个网络接口  一台接入互联网的计算机至少有一个IP地址 我感觉应该是一块无线网卡对应一个ip地址  分类  按格式  IPV4  32位整数 耗尽   IPV6    按范围  公网 内网（局域网）">
<meta property="og:locale" content="en">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1gemkh4bst8j32461ljh0o.jpg">
<meta property="og:updated_time" content="2020-08-25T01:56:37.440Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="网络编程">
<meta name="twitter:description" content="网路编程网络编程基础计算机网络 多台计算机通过通讯线路相连接  互联网 将所有计算机网络相连接  协议  TCP IP    IP地址 标识一个网络接口  一台接入互联网的计算机至少有一个IP地址 我感觉应该是一块无线网卡对应一个ip地址  分类  按格式  IPV4  32位整数 耗尽   IPV6    按范围  公网 内网（局域网）">
<meta name="twitter:image" content="http://ww1.sinaimg.cn/large/005VT09Qly1gemkh4bst8j32461ljh0o.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2020/05/09/网络编程/">





  <title>网络编程 | Ming</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?2ff12830577cde1e94dd80bdcf083398";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Ming</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br>
            
            Commonweal 404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="Searching..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/05/09/网络编程/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Ming">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/arina.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Ming">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">网络编程</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2020-05-09T22:24:07+08:00">
                2020-05-09
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Network/" itemprop="url" rel="index">
                    <span itemprop="name">Network</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">Words count in article&#58;</span>
                
                <span title="Words count in article">
                  3.1k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">Reading time &asymp;</span>
                
                <span title="Reading time">
                  13
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="网路编程"><a href="#网路编程" class="headerlink" title="网路编程"></a>网路编程</h1><h2 id="网络编程基础"><a href="#网络编程基础" class="headerlink" title="网络编程基础"></a>网络编程基础</h2><h3 id="计算机网络"><a href="#计算机网络" class="headerlink" title="计算机网络"></a>计算机网络</h3><ul>
<li>多台计算机通过通讯线路相连接</li>
</ul>
<h3 id="互联网"><a href="#互联网" class="headerlink" title="互联网"></a>互联网</h3><ul>
<li><p>将所有计算机网络相连接</p>
</li>
<li><p>协议</p>
<ul>
<li>TCP</li>
<li>IP</li>
</ul>
</li>
</ul>
<h3 id="IP地址"><a href="#IP地址" class="headerlink" title="IP地址"></a>IP地址</h3><ul>
<li><p>标识一个网络接口</p>
</li>
<li><p>一台接入互联网的计算机至少有一个IP地址</p>
<p>我感觉应该是一块无线网卡对应一个ip地址</p>
</li>
<li><p>分类</p>
<ul>
<li><p>按格式</p>
<ul>
<li><p>IPV4</p>
<ul>
<li>32位整数</li>
<li>耗尽</li>
</ul>
</li>
<li><p>IPV6</p>
</li>
</ul>
</li>
<li><p>按范围</p>
<ul>
<li>公网</li>
<li>内网（局域网）</li>
</ul>
</li>
</ul>
</li>
</ul>
<a id="more"></a>

<h3 id="网络号"><a href="#网络号" class="headerlink" title="网络号"></a>网络号</h3><ul>
<li><p>获得</p>
<ul>
<li>ip地址经过子网掩码过滤</li>
</ul>
</li>
<li><p>用途</p>
<ul>
<li><p>网络号相同</p>
<ul>
<li>设备在同一个网络下，可以直接通信</li>
</ul>
</li>
<li><p>网络号不同</p>
<ul>
<li>设备不在一个网络下，要依靠路由器或交换机通信</li>
</ul>
</li>
</ul>
</li>
</ul>
<h3 id="网络设备"><a href="#网络设备" class="headerlink" title="网络设备"></a>网络设备</h3><ul>
<li><p>网关</p>
<ul>
<li>路由器</li>
<li>交换机</li>
</ul>
</li>
</ul>
<h3 id="路由"><a href="#路由" class="headerlink" title="路由"></a>路由</h3><ul>
<li>通过网关把一个网络的数据包发送到另一个网络</li>
</ul>
<h3 id="域名"><a href="#域名" class="headerlink" title="域名"></a>域名</h3><ul>
<li><p>为什么存在？</p>
<ul>
<li><p>因为IP地址太难记</p>
<p>也就是说 域名就是给ip地址起个小名儿 叫起来方便</p>
</li>
</ul>
</li>
<li><p>特殊的localhost</p>
<ul>
<li><p>因为特殊所以特殊</p>
<p>我看了C盘windows下的那个hosts文件，就像是字典一样，一个ip地址对应一个域名，我怀疑域名解析就是靠这个实现的。</p>
<ul>
<li>127.0.0.1</li>
</ul>
</li>
</ul>
</li>
</ul>
<h3 id="网络模型"><a href="#网络模型" class="headerlink" title="网络模型"></a>网络模型</h3><ul>
<li><p>分层</p>
<ul>
<li><p>原因</p>
<ul>
<li>因为复杂所以分层</li>
</ul>
</li>
<li><p>目的</p>
<ul>
<li>简化网络操作</li>
</ul>
</li>
<li><p>有哪些层呢</p>
<ul>
<li><p>应用层</p>
<ul>
<li>提供应用程序之间的通信</li>
</ul>
</li>
<li><p>传输层</p>
<ul>
<li>提供端到端的传输</li>
</ul>
</li>
<li><p>IP层</p>
<ul>
<li>根据目标地址选择路由传输数据</li>
</ul>
</li>
<li><p>网络接口层</p>
<ul>
<li>处理数据然后通过物理设备（网线\wifi）传输</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<h3 id="协议"><a href="#协议" class="headerlink" title="协议"></a>协议</h3><ul>
<li><p>作用</p>
<ul>
<li>交易之前总得商量好吧</li>
</ul>
</li>
<li><p>常用协议</p>
<ul>
<li><p>IP协议</p>
<ul>
<li><p>负责发数据包</p>
<p>好像是瞎jb‘发的 据说不保证顺序 正确与否<br>也不知道是不是真的</p>
</li>
</ul>
</li>
<li><p>TCP协议</p>
<ul>
<li><p>负责控制数据包传输</p>
<p>负责的协议，通过一些手段（目前我还听不懂的名词）保证可靠、正确、稳定。</p>
<ul>
<li>建立连接</li>
<li>传输数据</li>
<li>断开连接</li>
</ul>
</li>
</ul>
</li>
<li><p>UDP</p>
<ul>
<li><p>VS TCP</p>
<ul>
<li><p>UDP完任务型选手</p>
<p>我只管传输数据，有没有人接受我不care</p>
</li>
<li><p>无连接</p>
</li>
<li><p>速度更快</p>
</li>
<li><p>协议更简单</p>
</li>
<li><p>质量更垃圾</p>
</li>
<li><p>数据必丢失</p>
</li>
</ul>
</li>
<li><p>应用</p>
<ul>
<li><p>能容忍数据丢失的场合</p>
<p>据说音视频通话比较常用，我想也是，能听来或者看来个百分之八九十就可了。</p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 id="TCP编程"><a href="#TCP编程" class="headerlink" title="TCP编程"></a>TCP编程</h2><h3 id="socket"><a href="#socket" class="headerlink" title="socket"></a>socket</h3><p>据说socket、tcp和部分ip的功能是由操作系统实现并提供的，不同的语言只是对操作系统提供的接口进行了一些包装</p>
<ul>
<li><p>啥是socket</p>
<ul>
<li>application通过socket在网络间传输数据</li>
<li>socket通过TCP/IP协议在网络间传输数据</li>
</ul>
</li>
<li><p>为啥需要socket</p>
<ul>
<li><p>ip地址是网卡的标识</p>
<p>说的粗糙一点就是 设备的标识</p>
</li>
<li><p>ip地址过于粗糙</p>
</li>
<li><p>socket精确到application</p>
</li>
</ul>
</li>
<li><p>socket长啥样啊</p>
<ul>
<li>ip地址再加点儿料（端口）</li>
</ul>
</li>
<li><p>端口</p>
<ul>
<li><p>为啥需要端口啊</p>
<p>ip地址标识网络接口，if我的电脑有一个网卡，这个网卡有一个ip地址，我的电脑上运行了好多需要联网的应用，比如qq、战网、steam，还有很多其他应用。我的网卡对于从远方发过来的包照单全收，但这些包都是名花有主的，因为物质资料还没有到极大丰富的地步，所以不能实行共产主义平均分配或者每人来一份，我们得按需分配，按闹分配，比如qq你只能领取属于自己的包，那怎么实现这样的需求呢？<br>咱这样，你们每个应用，给自己整一个端口，比如战网，你的port是988，那我网卡以后就通过这个端口跟你keep touch，其他应用都要有自己的端口，俺网卡按照包的标识，按照咱约定好的端口，按需分配，这样就解决问题了。</p>
<ul>
<li>因为socket</li>
</ul>
</li>
<li><p>特权端口</p>
<p>比如我的应用是用一个普通user打开的，那这个应用就不能使用1024以下的端口</p>
<ul>
<li>1024以下需要管理员权限</li>
</ul>
</li>
</ul>
</li>
<li><p>socket编程</p>
<ul>
<li><p>服务器端</p>
<ul>
<li><p>服务客户端的端</p>
</li>
<li><p>服务端会监听某个端口</p>
</li>
</ul>
</li>
</ul>
<ul>
<li><p>从端口获得数据包然后服务客户端（我猜的</p>
<ul>
<li><p>代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> Laboratory;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.xml.crypto.Data;</span><br><span class="line"><span class="keyword">import</span> java.io.*;</span><br><span class="line"><span class="keyword">import</span> java.net.*;</span><br><span class="line"><span class="keyword">import</span> java.nio.charset.StandardCharsets;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Experiment</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        <span class="comment">//服务器端，可能会有很多客户端请求与我共舞</span></span><br><span class="line">        <span class="comment">//监听指定的端口，可以指定ip地址，ip地址标识网络接口，如果不指定ip地址，表明监听计算机上的所有网络接口</span></span><br><span class="line">        ServerSocket serverSocket = <span class="keyword">new</span> ServerSocket(<span class="number">6666</span>);</span><br><span class="line">        System.out.println(<span class="string">"server is running"</span>);</span><br><span class="line">        <span class="comment">//处理和客户端之间的连接</span></span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">            <span class="comment">//ServerSocket的accept方法，如果有客户端请求连接，我就整个socket对象给他，如果没有人请求连接，这个方法就会block</span></span><br><span class="line">            Socket socket = serverSocket.accept();</span><br><span class="line">            System.out.println(<span class="string">"Connected from "</span> + socket.getRemoteSocketAddress());</span><br><span class="line">            Thread thread = <span class="keyword">new</span> Handler(socket);</span><br><span class="line">            thread.start();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Handler</span> <span class="keyword">extends</span> <span class="title">Thread</span> </span>&#123;</span><br><span class="line">    Socket socket;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Handler</span><span class="params">(Socket socket)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.socket = socket;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> (InputStream inputStream = <span class="keyword">this</span>.socket.getInputStream()) &#123;</span><br><span class="line">            <span class="keyword">try</span> (OutputStream outputStream = <span class="keyword">this</span>.socket.getOutputStream()) &#123;</span><br><span class="line">                handle(inputStream, outputStream);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="keyword">this</span>.socket.close();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (IOException ioe) &#123;</span><br><span class="line">            &#125;</span><br><span class="line">            System.out.println(<span class="string">"Client disconnected"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">handle</span><span class="params">(InputStream inputStream, OutputStream outputStream)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> writer = <span class="keyword">new</span> BufferedWriter(<span class="keyword">new</span> OutputStreamWriter(outputStream, StandardCharsets.UTF_8));</span><br><span class="line">        <span class="keyword">var</span> reader = <span class="keyword">new</span> BufferedReader(<span class="keyword">new</span> InputStreamReader(inputStream, StandardCharsets.UTF_8));</span><br><span class="line">        writer.write(<span class="string">"Fku\n"</span>);</span><br><span class="line">        writer.flush();</span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">            String s = reader.readLine();</span><br><span class="line">            <span class="keyword">if</span> (s.equals(<span class="string">"bye"</span>)) &#123;</span><br><span class="line">                writer.write(<span class="string">"bye too"</span>);</span><br><span class="line">                writer.flush();</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            writer.write(<span class="string">"fku 3000 times "</span> + s);</span><br><span class="line">           writer.flush();</span><br><span class="line">        &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">	</span><br></pre></td></tr></table></figure>


</li>
</ul>
</li>
</ul>
</li>
</ul>
<pre><code>- 客户端

  - 主动连接服务器的ip和指定端口

  - 代码

    <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> Laboratory;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.*;</span><br><span class="line"><span class="keyword">import</span> java.net.Socket;</span><br><span class="line"><span class="keyword">import</span> java.nio.charset.StandardCharsets;</span><br><span class="line"><span class="keyword">import</span> java.util.Scanner;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Experiment</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        <span class="comment">//客户端的TCP程序</span></span><br><span class="line">        <span class="comment">//连接指定的服务器和端口，如果连接成功，会返回一个socket实例，用于日后的通信</span></span><br><span class="line">        Socket socket = <span class="keyword">new</span> Socket(<span class="string">"localhost"</span>, <span class="number">6666</span>);</span><br><span class="line">        <span class="keyword">try</span> (InputStream inputStream = socket.getInputStream()) &#123;</span><br><span class="line">            <span class="keyword">try</span> (OutputStream outputStream = socket.getOutputStream()) &#123;</span><br><span class="line">                handle(inputStream, outputStream);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        socket.close();</span><br><span class="line">        System.out.println(<span class="string">"Disconnected"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">handle</span><span class="params">(InputStream inputStream, OutputStream outputStream)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> reader = <span class="keyword">new</span> BufferedReader(<span class="keyword">new</span> InputStreamReader(inputStream, StandardCharsets.UTF_8));</span><br><span class="line">        <span class="keyword">var</span> writer = <span class="keyword">new</span> BufferedWriter(<span class="keyword">new</span> OutputStreamWriter(outputStream, StandardCharsets.UTF_8));</span><br><span class="line">        Scanner scanner = <span class="keyword">new</span> Scanner(System.in);</span><br><span class="line">        System.out.println(<span class="string">"[server] "</span> + reader.readLine());</span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">            System.out.print(<span class="string">"&gt;&gt;&gt; "</span>);       <span class="comment">//打印提示</span></span><br><span class="line">            String s = scanner.nextLine();      <span class="comment">//读取一行输入</span></span><br><span class="line">             writer.write(s);</span><br><span class="line">            writer.newLine();</span><br><span class="line">          writer.flush();</span><br><span class="line">            String str = reader.readLine();</span><br><span class="line">            System.out.println(<span class="string">"&lt;&lt;&lt;"</span> + str);</span><br><span class="line">            <span class="keyword">if</span> (str.equals(<span class="string">"bye"</span>)) &#123;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>




- 编程使得客户端和服务端进行通信</code></pre><h3 id="三次握手"><a href="#三次握手" class="headerlink" title="三次握手"></a>三次握手</h3><p>tcp是要和服务器建立连接的啊</p>
<ul>
<li>屌丝：可以吗？</li>
<li>女神：可以，你想什么时候？</li>
<li>屌丝：今ここだ</li>
</ul>
<h2 id="UDP编程"><a href="#UDP编程" class="headerlink" title="UDP编程"></a>UDP编程</h2><h3 id="UDP-VS-TCP"><a href="#UDP-VS-TCP" class="headerlink" title="UDP VS TCP"></a>UDP VS TCP</h3><ul>
<li><p>UDP不需要建立连接</p>
<p>当然也就不需要断开连接</p>
</li>
<li><p>UDP没有流的概念</p>
</li>
<li><p>两者的端口相互独立</p>
<p>就是 假如有两个应用，一个用UDP，一个用TCP，就算两个用一个端口也没事儿</p>
</li>
</ul>
<h3 id="服务器端"><a href="#服务器端" class="headerlink" title="服务器端"></a>服务器端</h3><ul>
<li><p>监听指定的端口</p>
</li>
<li><p>代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> Laboratory;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.net.DatagramPacket;</span><br><span class="line"><span class="keyword">import</span> java.net.DatagramSocket;</span><br><span class="line"><span class="keyword">import</span> java.net.SocketException;</span><br><span class="line"><span class="keyword">import</span> java.nio.charset.StandardCharsets;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Experiment</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        <span class="comment">//服务端的操作：准备一个datagramSocket对象，利用他的receive和send方法接收和发送数据</span></span><br><span class="line">        <span class="comment">//服务器端首先使用如下语句在指定的端口监听UDP数据包：</span></span><br><span class="line">        DatagramSocket datagramSocket = <span class="keyword">new</span> DatagramSocket(<span class="number">6666</span>);</span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">            <span class="comment">//准备一个byte[]类型的缓冲包用来接收来自端口的数据</span></span><br><span class="line">            <span class="keyword">byte</span>[] buffer = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span>];</span><br><span class="line">            <span class="comment">//通过DatagramPacket对象的方法receive接收数据包</span></span><br><span class="line">            DatagramPacket datagramPacket = <span class="keyword">new</span> DatagramPacket(buffer, buffer.length);</span><br><span class="line">            datagramSocket.receive(datagramPacket);</span><br><span class="line">            <span class="comment">//通过DatagramPacket的getOffset和getLength方法确定接收到的数据在缓冲区的起始位置</span></span><br><span class="line">            String s = <span class="keyword">new</span> String(datagramPacket.getData(), datagramPacket.getOffset(), datagramPacket.getLength(), StandardCharsets.UTF_8);</span><br><span class="line">            <span class="keyword">byte</span>[] data = <span class="string">"ACK"</span>.getBytes(StandardCharsets.UTF_8);</span><br><span class="line">            datagramPacket.setData(data);</span><br><span class="line">            datagramSocket.send(datagramPacket);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>




</li>
</ul>
<h3 id="客户端"><a href="#客户端" class="headerlink" title="客户端"></a>客户端</h3><ul>
<li><p>操作</p>
<ul>
<li>向服务器发送UDP包</li>
<li>接收服务器返回的UDP包</li>
</ul>
</li>
<li><p>代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> Laboratory;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.xml.crypto.Data;</span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.net.DatagramPacket;</span><br><span class="line"><span class="keyword">import</span> java.net.DatagramSocket;</span><br><span class="line"><span class="keyword">import</span> java.net.InetAddress;</span><br><span class="line"><span class="keyword">import</span> java.net.SocketException;</span><br><span class="line"><span class="keyword">import</span> java.nio.charset.StandardCharsets;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Experiment</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        <span class="comment">//客户端</span></span><br><span class="line">        <span class="comment">//客户端创建DatagramSocket的时候不需要指定端口，分配端口这个活儿是OS干的，所以说OS是程序员的好朋友</span></span><br><span class="line">        DatagramSocket datagramSocket = <span class="keyword">new</span> DatagramSocket();</span><br><span class="line">        <span class="comment">//此处有别于服务器端，服务器端可以循环到天荒地老，但客户端有所不同，需要设置最长等待时间，过期不候</span></span><br><span class="line">        datagramSocket.setSoTimeout(<span class="number">1000</span>);</span><br><span class="line">        <span class="comment">//UDP不需要建立连接，没错，这里的connect并不是真连接，而是想把服务器的ip和端口保存下来，以便之后向服务器发送UDP数据包</span></span><br><span class="line">        datagramSocket.connect(InetAddress.getByName(<span class="string">"localhost"</span>), <span class="number">6666</span>);</span><br><span class="line">        <span class="comment">//现在可以发送数据了</span></span><br><span class="line">        <span class="comment">//先来点数据</span></span><br><span class="line">        <span class="keyword">byte</span>[] data = <span class="string">"What's going on?"</span>.getBytes();</span><br><span class="line">        <span class="comment">//和DatagramPacket绑在一起</span></span><br><span class="line">        DatagramPacket datagramPacket = <span class="keyword">new</span> DatagramPacket(data, data.length);</span><br><span class="line">        <span class="comment">//通过Socket的方法send将Packet发送到服务器，必须是先发再收，不然服务器不知道客户端的ip和端口号</span></span><br><span class="line">        datagramSocket.send(datagramPacket);</span><br><span class="line">        <span class="comment">//发送之后就可以接受数据了</span></span><br><span class="line">        <span class="comment">//接受数据，和服务端一样</span></span><br><span class="line">        <span class="comment">//先准备一个byte数组用来接受数据</span></span><br><span class="line">        <span class="keyword">byte</span>[] buffer = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span>];</span><br><span class="line">        <span class="comment">//把buffer和packet绑定起来</span></span><br><span class="line">        datagramPacket = <span class="keyword">new</span> DatagramPacket(buffer, buffer.length);</span><br><span class="line">        <span class="comment">//通过socket的receive方法接受数据存到预先设定的packet里</span></span><br><span class="line">        datagramSocket.receive(datagramPacket);</span><br><span class="line">        <span class="comment">//转换成String</span></span><br><span class="line">        String str = <span class="keyword">new</span> String(datagramPacket.getData(), datagramPacket.getOffset(), datagramPacket.getLength());</span><br><span class="line">        <span class="comment">//如果可以，可以选择断开连接</span></span><br><span class="line">        <span class="comment">//既然不存在连接，当然也就不存在断开的对象，确实如此，此处的disconnect只是把socket对象恢复出厂设置，以便于socket可以再利用而已</span></span><br><span class="line">        datagramSocket.disconnect();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>




</li>
</ul>
<h2 id="Email"><a href="#Email" class="headerlink" title="Email"></a>Email</h2><h3 id="发送"><a href="#发送" class="headerlink" title="发送"></a>发送</h3><ul>
<li><p>传统的邮件</p>
<ul>
<li>投递到邮局——邮局2——邮局3——信箱</li>
</ul>
</li>
<li><p>电子邮件</p>
<ul>
<li>从用户的邮箱软件发送到服务器——服务器2——服务器3——邮箱</li>
</ul>
</li>
<li><p>邮箱软件</p>
<ul>
<li>MUA</li>
<li>Mail User Agent</li>
</ul>
</li>
<li><p>邮件服务器</p>
<ul>
<li><p>MTA</p>
</li>
<li><p>MDA</p>
<ul>
<li>邮件最终的归属</li>
<li>或许是某个服务器的某块硬盘</li>
</ul>
</li>
</ul>
</li>
<li><p>代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><span class="line">  </span><br><span class="line"> <span class="keyword">import</span> javax.mail.*;</span><br><span class="line"> <span class="keyword">import</span> javax.mail.internet.AddressException;</span><br><span class="line"> <span class="keyword">import</span> javax.mail.internet.InternetAddress;</span><br><span class="line"> <span class="keyword">import</span> javax.mail.internet.MimeMessage;</span><br><span class="line"> <span class="keyword">import</span> java.util.Properties;</span><br><span class="line">  </span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Mail</span> </span>&#123;</span><br><span class="line">     <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> MessagingException </span>&#123;</span><br><span class="line">         String smtp = <span class="string">"smtp.qq.com"</span>;</span><br><span class="line">         String username = <span class="string">"674602921@qq.com"</span>;</span><br><span class="line">         String password = <span class="string">"grzbslakcefkbceg"</span>;</span><br><span class="line">         Properties properties = <span class="keyword">new</span> Properties();</span><br><span class="line">         properties.put(<span class="string">"mail.smtp.host"</span>, smtp);</span><br><span class="line">         properties.put(<span class="string">"mail.smtp.port"</span>, <span class="number">465</span>);</span><br><span class="line">         properties.put(<span class="string">"mail.smtp.auth"</span>, <span class="string">"true"</span>);</span><br><span class="line">         properties.put(<span class="string">"mail.starttls.enable"</span>, <span class="string">"true"</span>);</span><br><span class="line">         properties.put(<span class="string">"mail.smtp.socketFactory.class"</span>, <span class="string">"javax.net.ssl.SSLSocketFactory"</span>);</span><br><span class="line">         Session session = Session.getInstance(properties, <span class="keyword">new</span> Authenticator() &#123;</span><br><span class="line">             <span class="meta">@Override</span></span><br><span class="line">             <span class="function"><span class="keyword">protected</span> PasswordAuthentication <span class="title">getPasswordAuthentication</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                 <span class="keyword">return</span> <span class="keyword">new</span> PasswordAuthentication(username, password);</span><br><span class="line">             &#125;</span><br><span class="line">         &#125;);</span><br><span class="line">         session.setDebug(<span class="keyword">true</span>);</span><br><span class="line">         MimeMessage message = <span class="keyword">new</span> MimeMessage(session);</span><br><span class="line">         message.setFrom(<span class="keyword">new</span> InternetAddress(<span class="string">"674602921@qq.com"</span>));</span><br><span class="line">         message.setRecipient(Message.RecipientType.TO, <span class="keyword">new</span> InternetAddress(<span class="string">"ljm158675@gmail.com"</span>));</span><br><span class="line">         message.setSubject(<span class="string">"Hey"</span>, <span class="string">"UTF-8"</span>);</span><br><span class="line">         message.setText(<span class="string">"Java,please!"</span>);</span><br><span class="line">         Transport.send(message);</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br><span class="line">  </span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Mail</span> </span>&#123;</span><br><span class="line">     <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> MessagingException </span>&#123;</span><br><span class="line">         String smtp = <span class="string">"smtp.qq.com"</span>;</span><br><span class="line">         String username = <span class="string">"674602921@qq.com"</span>;</span><br><span class="line">         String password = <span class="string">"grzbslakcefkbceg"</span>;</span><br><span class="line">         Properties properties = <span class="keyword">new</span> Properties();</span><br><span class="line">         properties.put(<span class="string">"mail.smtp.host"</span>, smtp);</span><br><span class="line">         properties.put(<span class="string">"mail.smtp.port"</span>, <span class="number">465</span>);</span><br><span class="line">         properties.put(<span class="string">"mail.smtp.auth"</span>, <span class="string">"true"</span>);</span><br><span class="line">         properties.put(<span class="string">"mail.starttls.enable"</span>, <span class="string">"true"</span>);</span><br><span class="line">         properties.put(<span class="string">"mail.smtp.socketFactory.class"</span>, <span class="string">"javax.net.ssl.SSLSocketFactory"</span>);</span><br><span class="line">         Session session = Session.getInstance(properties, <span class="keyword">new</span> Authenticator() &#123;</span><br><span class="line">             <span class="meta">@Override</span></span><br><span class="line">             <span class="function"><span class="keyword">protected</span> PasswordAuthentication <span class="title">getPasswordAuthentication</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                 <span class="keyword">return</span> <span class="keyword">new</span> PasswordAuthentication(username, password);</span><br><span class="line">             &#125;</span><br><span class="line">         &#125;);</span><br><span class="line">         session.setDebug(<span class="keyword">true</span>);</span><br><span class="line">         MimeMessage message = <span class="keyword">new</span> MimeMessage(session);</span><br><span class="line">         message.setFrom(<span class="keyword">new</span> InternetAddress(<span class="string">"674602921@qq.com"</span>));</span><br><span class="line">         message.setRecipient(Message.RecipientType.TO, <span class="keyword">new</span> InternetAddress(<span class="string">"ljm158675@gmail.com"</span>));</span><br><span class="line">         message.setSubject(<span class="string">"Hey"</span>, <span class="string">"UTF-8"</span>);</span><br><span class="line">         message.setText(<span class="string">"Java,please!"</span>);</span><br><span class="line">         Transport.send(message);</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>


</li>
</ul>
<h3 id="接收"><a href="#接收" class="headerlink" title="接收"></a>接收</h3><ul>
<li><p>代码</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><span class="line">  </span><br><span class="line">import com.sun.mail.pop3.POP3SSLStore;</span><br><span class="line">  </span><br><span class="line">  </span><br><span class="line">import javax.mail.*;</span><br><span class="line">import javax.mail.internet.AddressException;</span><br><span class="line">import javax.mail.internet.InternetAddress;</span><br><span class="line">import javax.mail.internet.MimeMessage;</span><br><span class="line">import javax.mail.internet.MimeUtility;</span><br><span class="line">import java.io.IOException;</span><br><span class="line">import java.util.Properties;</span><br><span class="line">  </span><br><span class="line">public class Mail &#123;</span><br><span class="line">    public static void main(String[] args) throws MessagingException, IOException &#123;</span><br><span class="line">        String host = &quot;pop3.example.com&quot;;</span><br><span class="line">        String username = &quot;bob@example.com&quot;;</span><br><span class="line">        String password = &quot;********&quot;;</span><br><span class="line">        int port = 995;</span><br><span class="line">        Properties properties = new Properties();</span><br><span class="line">        properties.setProperty(&quot;mail.store.protocol&quot;, &quot;pop3&quot;);</span><br><span class="line">        properties.setProperty(&quot;mail.pop3.host&quot;, host);</span><br><span class="line">        properties.setProperty(&quot;mail.pop3.port&quot;, String.valueOf(port));</span><br><span class="line">        properties.put(&quot;mail.smtp.socketFactory.class&quot;, &quot;javax.net.ssl.SSLSocketFactory&quot;);</span><br><span class="line">        properties.put(&quot;mail.smtp.socketFactory.port&quot;, String.valueOf(port));</span><br><span class="line">        URLName urlName = new URLName(&quot;pop3&quot;, host, port, &quot;&quot;, username, password);</span><br><span class="line">        Session session = Session.getInstance(properties, null);</span><br><span class="line">        session.setDebug(true);</span><br><span class="line">        Store store = new POP3SSLStore(session, urlName);</span><br><span class="line">        store.connect();</span><br><span class="line">        // 获取收件箱:</span><br><span class="line">        Folder folder = store.getFolder(&quot;INBOX&quot;);</span><br><span class="line">// 以读写方式打开:</span><br><span class="line">        folder.open(Folder.READ_WRITE);</span><br><span class="line">// 打印邮件总数/新邮件数量/未读数量/已删除数量:</span><br><span class="line">        System.out.println(&quot;Total messages: &quot; + folder.getMessageCount());</span><br><span class="line">        System.out.println(&quot;New messages: &quot; + folder.getNewMessageCount());</span><br><span class="line">        System.out.println(&quot;Unread messages: &quot; + folder.getUnreadMessageCount());</span><br><span class="line">        System.out.println(&quot;Deleted messages: &quot; + folder.getDeletedMessageCount());</span><br><span class="line">// 获取每一封邮件:</span><br><span class="line">        Message[] messages = folder.getMessages();</span><br><span class="line">        for (Message message : messages) &#123;</span><br><span class="line">            // 打印每一封邮件:</span><br><span class="line">            printMessage((MimeMessage) message);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  </span><br><span class="line">    static void printMessage(MimeMessage msg) throws IOException, MessagingException &#123;</span><br><span class="line">        // 邮件主题:</span><br><span class="line">        System.out.println(&quot;Subject: &quot; + MimeUtility.decodeText(msg.getSubject()));</span><br><span class="line">        // 发件人:</span><br><span class="line">        Address[] froms = msg.getFrom();</span><br><span class="line">        InternetAddress address = (InternetAddress) froms[0];</span><br><span class="line">        String personal = address.getPersonal();</span><br><span class="line">        String from = personal == null ? address.getAddress() : (MimeUtility.decodeText(personal) + &quot; &lt;&quot; + address.getAddress() + &quot;&gt;&quot;);</span><br><span class="line">        System.out.println(&quot;From: &quot; + from);</span><br><span class="line">        // 继续打印收件人:</span><br><span class="line">    &#125;</span><br><span class="line">  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


</li>
</ul>
<h2 id="HTTP编程"><a href="#HTTP编程" class="headerlink" title="HTTP编程"></a>HTTP编程</h2><h3 id="建立TCP连接"><a href="#建立TCP连接" class="headerlink" title="建立TCP连接"></a>建立TCP连接</h3><h3 id="请求（HTTP，浏览器）"><a href="#请求（HTTP，浏览器）" class="headerlink" title="请求（HTTP，浏览器）"></a>请求（HTTP，浏览器）</h3><ul>
<li>HTTP HEADER</li>
<li>HTTP BODY</li>
</ul>
<h3 id="响应（HTTP，服务器）"><a href="#响应（HTTP，服务器）" class="headerlink" title="响应（HTTP，服务器）"></a>响应（HTTP，服务器）</h3><img referrerpolicy="no-referrer" src="http://ww1.sinaimg.cn/large/005VT09Qly1gemkh4bst8j32461ljh0o.jpg">

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>赠人玫瑰，手有余香</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>Donate</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="Ming WeChat Pay">
        <p>WeChat Pay</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Ming Alipay">
        <p>Alipay</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/05/09/http/" rel="next" title="http">
                <i class="fa fa-chevron-left"></i> http
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/05/09/反射/" rel="prev" title="反射">
                反射 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/arina.jpg" alt="Ming">
            
              <p class="site-author-name" itemprop="name">Ming</p>
              <p class="site-description motion-element" itemprop="description">Come on, check me out!</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">153</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/carpediemtal" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mail:674602921@qq.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="qq:674602921" target="_blank" title="QQ">
                      
                        <i class="fa fa-fw fa-qq"></i>QQ</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="overwatchID:SEKAI#51158" target="_blank" title="Overwatch">
                      
                        <i class="fa fa-fw fa-gamepad"></i>Overwatch</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.treasurew.com/" title="treasurew" target="_blank">treasurew</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#网路编程"><span class="nav-number">1.</span> <span class="nav-text">网路编程</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#网络编程基础"><span class="nav-number">1.1.</span> <span class="nav-text">网络编程基础</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#计算机网络"><span class="nav-number">1.1.1.</span> <span class="nav-text">计算机网络</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#互联网"><span class="nav-number">1.1.2.</span> <span class="nav-text">互联网</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#IP地址"><span class="nav-number">1.1.3.</span> <span class="nav-text">IP地址</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#网络号"><span class="nav-number">1.1.4.</span> <span class="nav-text">网络号</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#网络设备"><span class="nav-number">1.1.5.</span> <span class="nav-text">网络设备</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#路由"><span class="nav-number">1.1.6.</span> <span class="nav-text">路由</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#域名"><span class="nav-number">1.1.7.</span> <span class="nav-text">域名</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#网络模型"><span class="nav-number">1.1.8.</span> <span class="nav-text">网络模型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#协议"><span class="nav-number">1.1.9.</span> <span class="nav-text">协议</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#TCP编程"><span class="nav-number">1.2.</span> <span class="nav-text">TCP编程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#socket"><span class="nav-number">1.2.1.</span> <span class="nav-text">socket</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#三次握手"><span class="nav-number">1.2.2.</span> <span class="nav-text">三次握手</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#UDP编程"><span class="nav-number">1.3.</span> <span class="nav-text">UDP编程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#UDP-VS-TCP"><span class="nav-number">1.3.1.</span> <span class="nav-text">UDP VS TCP</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#服务器端"><span class="nav-number">1.3.2.</span> <span class="nav-text">服务器端</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#客户端"><span class="nav-number">1.3.3.</span> <span class="nav-text">客户端</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Email"><span class="nav-number">1.4.</span> <span class="nav-text">Email</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#发送"><span class="nav-number">1.4.1.</span> <span class="nav-text">发送</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#接收"><span class="nav-number">1.4.2.</span> <span class="nav-text">接收</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#HTTP编程"><span class="nav-number">1.5.</span> <span class="nav-text">HTTP编程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#建立TCP连接"><span class="nav-number">1.5.1.</span> <span class="nav-text">建立TCP连接</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#请求（HTTP，浏览器）"><span class="nav-number">1.5.2.</span> <span class="nav-text">请求（HTTP，浏览器）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#响应（HTTP，服务器）"><span class="nav-number">1.5.3.</span> <span class="nav-text">响应（HTTP，服务器）</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2019 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Ming</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">64.9k</span>
  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
